package com.ruoyi.cases.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.cases.domain.JlDailyStatistics;
import com.ruoyi.cases.domain.JlDealUser;
import com.ruoyi.cases.domain.JlQuantitativeType;
import com.ruoyi.cases.mapper.JlDailyStatisticsMapper;
import com.ruoyi.cases.mapper.JlDealUserMapper;
import com.ruoyi.cases.mapper.JlQuantitativeTypeMapper;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.cases.mapper.JlTroubleshootingTableMapper;
import com.ruoyi.cases.domain.JlTroubleshootingTable;
import com.ruoyi.cases.service.IJlTroubleshootingTableService;

import javax.annotation.Resource;

/**
 * 病害排查Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-05-16
 */
@Service
public class JlTroubleshootingTableServiceImpl implements IJlTroubleshootingTableService 
{
    @Autowired
    private JlTroubleshootingTableMapper jlTroubleshootingTableMapper;

    @Autowired
    private JlDealUserMapper jlDealUserMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private JlQuantitativeTypeMapper jlQuantitativeTypeMapper;

    @Resource
    private JlDailyStatisticsMapper jlDailyStatisticsMapper;
    /**
     * 查询病害排查
     * 
     * @param id 病害排查主键
     * @return 病害排查
     */
    @Override
    public JlTroubleshootingTable selectJlTroubleshootingTableById(String id)
    {
        JlTroubleshootingTable j = jlTroubleshootingTableMapper.selectJlTroubleshootingTableById(id);
        if(StringUtils.isNotNull(j.getOwnPersonnelStr())){
            List i = j.getOwnPersonnel()==null?new ArrayList():j.getOwnPersonnel();
            for(String str :j.getOwnPersonnelStr().split(",")){
                i.add(str);
            }
            j.setOwnPersonnel(i);
        }
        return j;
    }

    /**
     * 查询病害排查列表
     * 
     * @param jlTroubleshootingTable 病害排查
     * @return 病害排查
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<JlTroubleshootingTable> selectJlTroubleshootingTableList(JlTroubleshootingTable jlTroubleshootingTable)
    {
        if(StringUtils.isNotNull(jlTroubleshootingTable.getQuantitativeTypeId())){
            jlTroubleshootingTable.setBeyondQuota("");
        }
        return jlTroubleshootingTableMapper.selectJlTroubleshootingTableList(jlTroubleshootingTable);
    }

    /**
     * 新增病害排查
     * 
     * @param jlTroubleshootingTable 病害排查
     * @return 结果
     */
    @Override
    public int insertJlTroubleshootingTable(JlTroubleshootingTable jlTroubleshootingTable)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        jlTroubleshootingTable.setCreateTime(DateUtils.getNowDate());
        /*采用雪花算法设置数据唯一id*/
        jlTroubleshootingTable.setId(String.valueOf(IdUtil.getSnowflake().nextId()));
        /*设置用户信息*/
        jlTroubleshootingTable.setCreateTime(DateUtils.getNowDate());
        jlTroubleshootingTable.setCreateBy(String.valueOf(loginUser.getUserId()));
        jlTroubleshootingTable.setUpdateTime(DateUtils.getNowDate());
        jlTroubleshootingTable.setUpdateBy(String.valueOf(loginUser.getUserId()));
        jlTroubleshootingTable.setUserId(String.valueOf(loginUser.getUserId()));
        String insourcedName = "";
        /*判断是否存在自由人员字段 如存在 则说明当前操作为指派，将自由人员信息插入至中间表*/
        if(jlTroubleshootingTable.getOwnPersonnel() != null && jlTroubleshootingTable.getOwnPersonnel().size()>0){
            List<JlDealUser> jlDealUserList = new ArrayList<>();
            String personalUsername = "";
            for(String id : jlTroubleshootingTable.getOwnPersonnel()){
                String currentUsername = sysUserMapper.selectUserById(Long.parseLong(id)).getNickName();
                insourcedName += currentUsername +",";
                JlDealUser jlDealUser = new JlDealUser();
                jlDealUser.setId(String.valueOf(IdUtil.getSnowflake().nextId()));
                jlDealUser.setUserId(id);
                jlDealUser.setUserName(currentUsername);
                jlDealUser.setTroubleshootingId(jlTroubleshootingTable.getId());
                jlDealUser.setDealDate(jlTroubleshootingTable.getTroubleshootingTime());
                jlDealUser.setDeptId(String.valueOf(loginUser.getDeptId()));
                jlDealUserList.add(jlDealUser);
                personalUsername += currentUsername +",";
            }
            personalUsername = personalUsername.substring(0,personalUsername.length()-1);
            jlTroubleshootingTable.setPersonalUsername(personalUsername);
            /*批量插入至中间关系表*/
            int i = jlDealUserMapper.batchInsert(jlDealUserList);
            /*设置自由人员数量 和姓名*/
            jlTroubleshootingTable.setInsourcedNum(String.valueOf(jlTroubleshootingTable.getOwnPersonnel().size()));
            jlTroubleshootingTable.setInsourcedName(insourcedName.substring(0,insourcedName.length()-1));
        }
        jlTroubleshootingTable.setAssignDate(jlTroubleshootingTable.getTroubleshootingTime());
        /*如果作业项目id 不等于空，则对应选择的是定额项目*/
        if(jlTroubleshootingTable.getQuantitativeTypeId() != null && !"".equals(jlTroubleshootingTable.getQuantitativeTypeId())){
            JlQuantitativeType jlQuantitativeType =  jlQuantitativeTypeMapper.selectJlQuantitativeTypeById(jlTroubleshootingTable.getQuantitativeTypeId());
            jlTroubleshootingTable.setQuantitativeTypeName(jlQuantitativeType.getProjectName());
            /*每天额定完成工作量*/
            jlTroubleshootingTable.setQuantitativeTypeValue(jlQuantitativeType.getRatedNum());
            /*人工单位成本*/
            jlTroubleshootingTable.setQuantitativeLaborCost(jlQuantitativeType.getLaborCost());
            /*额定标准单位*/
            jlTroubleshootingTable.setQuantitativeRatedUnitValue(DictUtils.getDictLabel("jl_case_unit",String.valueOf(jlQuantitativeType.getRatedUnit())));
        }else{
            /*每天额定完成工作量*/
            jlTroubleshootingTable.setQuantitativeTypeValue("8");
            /*人工单位成本*/
            jlTroubleshootingTable.setQuantitativeLaborCost("1");
            /*额定标准单位*/
            jlTroubleshootingTable.setQuantitativeRatedUnitValue("小时");
            /*设置非定额项目名称*/
            jlTroubleshootingTable.setQuantitativeTypeName(jlTroubleshootingTable.getBeyondQuota());
        }
        return jlTroubleshootingTableMapper.insertJlTroubleshootingTable(jlTroubleshootingTable);
    }

    /**
     * 修改病害排查
     * 
     * @param jlTroubleshootingTable 病害排查
     * @return 结果
     */
    @Override
    public int updateJlTroubleshootingTable(JlTroubleshootingTable jlTroubleshootingTable)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        jlTroubleshootingTable.setUpdateTime(DateUtils.getNowDate());
        /*待审核时 校验是否有修改数据权限*/
        if("1".equals(jlTroubleshootingTable.getDataStatus()))
                jlTroubleshootingTable.setCreateBy(String.valueOf(loginUser.getUserId()));
        else
        /*如果数据状态为待审核 则保存提交时间*/
        if("3".equals(jlTroubleshootingTable.getDataStatus())){
            jlTroubleshootingTable.setUploadTime(DateUtils.getNowDate());
        }
        String insourcedName = "";
        /*判断是否存在自由人员字段 如存在 则说明当前操作为指派，将自由人员信息插入至中间表*/
        if(jlTroubleshootingTable.getOwnPersonnel() != null && jlTroubleshootingTable.getOwnPersonnel().size()>0){
            List<JlDealUser> jlDealUserList = new ArrayList<>();
            String personalUsername = "";
            /*清除原有自有人员关系表数据*/
            jlDealUserMapper.deleteHis(jlTroubleshootingTable.getId());
            for(String id : jlTroubleshootingTable.getOwnPersonnel()){
                String currentUsername = sysUserMapper.selectUserById(Long.parseLong(id)).getNickName();
                insourcedName += currentUsername +",";
                JlDealUser jlDealUser = new JlDealUser();
                jlDealUser.setId(String.valueOf(IdUtil.getSnowflake().nextId()));
                jlDealUser.setUserId(id);
                jlDealUser.setUserName(currentUsername);
                jlDealUser.setTroubleshootingId(jlTroubleshootingTable.getId());
                jlDealUser.setDealDate(jlTroubleshootingTable.getTroubleshootingTime());
                jlDealUser.setDeptId(String.valueOf(loginUser.getDeptId()));
                jlDealUserList.add(jlDealUser);
                personalUsername += currentUsername +",";
            }
            personalUsername = personalUsername.substring(0,personalUsername.length()-1);
            jlTroubleshootingTable.setPersonalUsername(personalUsername);
            /*批量插入至中间关系表*/
            int i = jlDealUserMapper.batchInsert(jlDealUserList);
            /*设置自由人员数量 和姓名*/
            jlTroubleshootingTable.setInsourcedNum(String.valueOf(jlTroubleshootingTable.getOwnPersonnel().size()));
            jlTroubleshootingTable.setInsourcedName(insourcedName.substring(0,insourcedName.length()-1));
        }

        /*如果作业项目id 不等于空，则对应选择的是定额项目*/
        if(jlTroubleshootingTable.getQuantitativeTypeId() != null && !"".equals(jlTroubleshootingTable.getQuantitativeTypeId())){
            JlQuantitativeType jlQuantitativeType =  jlQuantitativeTypeMapper.selectJlQuantitativeTypeById(jlTroubleshootingTable.getQuantitativeTypeId());
            jlTroubleshootingTable.setQuantitativeTypeName(jlQuantitativeType.getProjectName());
            /*每天额定完成工作量*/
            jlTroubleshootingTable.setQuantitativeTypeValue(jlQuantitativeType.getRatedNum());
            /*人工单位成本*/
            jlTroubleshootingTable.setQuantitativeLaborCost(jlQuantitativeType.getLaborCost());
            /*额定标准单位*/
            jlTroubleshootingTable.setQuantitativeRatedUnitValue(DictUtils.getDictLabel("jl_case_unit",String.valueOf(jlQuantitativeType.getRatedUnit())));
        }else{
            /*每天额定完成工作量*/
            jlTroubleshootingTable.setQuantitativeTypeValue("8");
            /*人工单位成本*/
            jlTroubleshootingTable.setQuantitativeLaborCost("1");
            /*额定标准单位*/
            jlTroubleshootingTable.setQuantitativeRatedUnitValue("小时");
            /*设置非定额项目名称*/
            jlTroubleshootingTable.setQuantitativeTypeName(jlTroubleshootingTable.getBeyondQuota());
        }

        /*固话表之前要提前需要先更新*/
        int returnNum =  jlTroubleshootingTableMapper.updateJlTroubleshootingTable(jlTroubleshootingTable);
        /*如果是已接收  则开始固话表操作*/
        if(jlTroubleshootingTable.getDataStatus() != null && !"".equals(jlTroubleshootingTable.getDataStatus()) &&jlTroubleshootingTable.getDataStatus().equals("3")){
            /*查询当前用户 对应指派日期的工作内容*/
            List<JlDailyStatistics> dailyInsertList = jlDailyStatisticsMapper.getDailyInsertData(jlTroubleshootingTable.getId());
            if(dailyInsertList.size()>0){
                System.out.println("需同步信息数量"+dailyInsertList.size());
                for(JlDailyStatistics jlDailyStatistics : dailyInsertList){
                    jlDailyStatistics.setId(String.valueOf(IdUtil.getSnowflake().nextId()));
                }
                /*逐条判断 当前用户当前日期存在固话数据泽更新 不存在则新增*/
                for(JlDailyStatistics j:dailyInsertList){
                    JlDailyStatistics item = checkDataExist(j);
                    /*设置审核人*/
                    j.setAssessorTime(DateUtils.getDate());
                    j.setAuditUserId(String.valueOf(loginUser.getUserId()));
                    j.setAssessorName(String.valueOf(SecurityUtils.getLoginUser().getUser().getNickName()));
                    /*先判断当天是否存在数据 若存在则更新*/
                    if(item != null){
                        /*已判定存在数据，再判定是否已设置当天定额标准，如已设置则更新奖励金额字段*/
                        /*金额无需计算*/
//                        if(item.getQuotaStandard() != null && !"".equals(item.getQuotaStandard())){
//                            BigDecimal bigDecimal = new BigDecimal(j.getRatedCoefficient());
//                            j.setRewardDeductionAmount(((bigDecimal.subtract(new BigDecimal("1"))).multiply(new BigDecimal(j.getParam())).multiply(new BigDecimal(item.getQuotaStandard()))).setScale(2, RoundingMode.HALF_UP).toString());
//                        }
                        jlDailyStatisticsMapper.updateData(j);
                    }else{
                        j.setId(String.valueOf(IdUtil.getSnowflake().nextId()));
                        jlDailyStatisticsMapper.insertJlDailyStatistics(j);
                    }
                }
            }
        }

        return returnNum;
    }

    private JlDailyStatistics checkDataExist(JlDailyStatistics j) {
        return jlDailyStatisticsMapper.checkDataExist(j);
    }

    /**
     * 批量删除病害排查
     * 
     * @param ids 需要删除的病害排查主键
     * @return 结果
     */
    @Override
    public int deleteJlTroubleshootingTableByIds(String[] ids)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        JlTroubleshootingTable jlTroubleshootingTable = new JlTroubleshootingTable();
        jlTroubleshootingTable.setCreateBy(String.valueOf(loginUser.getUserId()));
        jlTroubleshootingTable.setIds(ids);
        return jlTroubleshootingTableMapper.deleteJlTroubleshootingTableByIds(jlTroubleshootingTable);
    }

    /**
     * 删除病害排查信息
     * 
     * @param id 病害排查主键
     * @return 结果
     */
    @Override
    public int deleteJlTroubleshootingTableById(String id)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        JlTroubleshootingTable jlTroubleshootingTable = new JlTroubleshootingTable();
        jlTroubleshootingTable.setCreateBy(String.valueOf(loginUser.getUserId()));
        return jlTroubleshootingTableMapper.deleteJlTroubleshootingTableById(jlTroubleshootingTable);
    }

    @Override
    public SysUser getAuditMsg(String deptId) {
        return sysUserMapper.getAuditMsg(deptId);
    }
}
